import React, { Component } from "react";

import { Carousel, Modal, Toast } from "antd-mobile";

import NavHeader from "../../components/NavHeader";

import HousePackage from '../HousePackage'

import styles from './index.module.css'

import { BASE_URL } from "../../utils/url";
import { API } from "../../utils/api";
import { isAuth } from "../../utils/auth";

const BMap = window.BMapGL

export default class HouseDetail extends Component {
  constructor(props) {
    super(props)
    this.state = {
      // 房屋id
      id: this.props.match.params.id,
      // 房屋信息
      houseData: {},
      // 房屋信息是否加载完毕
      flag: false,
      // 轮播图高度
      imgHeight: 212,
      // 房源是否已收藏
      isFavorite: false
    }
  }

  renderMap(community, coord) {
    const { latitude, longitude } = coord
    const map = new BMap.Map('map')
    const point = {
      lat: latitude,
      lng: longitude
    }
    map.centerAndZoom(point, 17)

    const label = new window.BMapGL.Label('', {
      position: point,
    })

    label.setStyle({
      color: '#fff',
      textAlign: 'center',
      cursor: 'pointer',
      border: '0px solid rgb(255, 0, 0)',
      fontSize: '12px',
      padding: '0px',
      lineHeight: '40px',
      backgroundColor: '#7bc53e',
      borderRadius: '10%',
      borderTopLeftRadius: '0%'
    })
    label.setContent(
      `<span>${community}</span>
       <div class='${styles.arrow}'></div>
      `
    )
    map.addOverlay(label)

    // 添加常用控件
    map.addControl(new window.BMapGL.ZoomControl())
    map.addControl(new window.BMapGL.ScaleControl())
  }

  // 获取房屋数据
  async getHouseInfo() {
    const { id } = this.state
    let res = await API(`/houses/${id}`)
    this.setState({
      houseData: res.data.body,
      flag: true
    })
  }

  // 渲染轮播图结构
  renderSwipers() {
    const { flag } = this.state
    if (flag) {
      return this.state.houseData.houseImg.map(val => 
        <a
          key={val.id}
          href="http://www.alipay.com"
          style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
        >
          <img
            src={`${BASE_URL}${val}`}
            alt={val.alt}
            style={{ width: '100%', verticalAlign: 'center', height: this.state.imgHeight }}
          />
        </a>
      )
    }
  }

  changeFavorite = async () => {
    const { isFavorite, id } = this.state
    if (isAuth()) {
      if (isFavorite) {
        let res = await API.delete(`/user/favorites/${id}`)
        if (res.data.status === 200) {
          Toast.info('取消收藏', 0.5)
          this.setState({
            isFavorite: !isFavorite
          })
        } else {
          Toast.info('登录超时，请重新登录', 0.5)
        }
      } else {
        let res = await API.post(`/user/favorites/${id}`)
        if (res.data.status === 200) {
          Toast.info('已收藏', 0.5)
          this.setState({
            isFavorite: !isFavorite
          })
        } else {
          Toast.info('登录超时，请重新登录', 0.5)
        }
      }
    } else {
      Modal.alert('提示', '请登录后使用收藏功能', [
        { text: '取消', onPress: () => null },
        { text: '去登录', onPress: () => this.props.history.push('/login', {
          from: this.props.location
        })},
      ])  
    }

  }

  checkFavorite = async () => {
    if (isAuth()) {
      const { id } = this.state
      let res = await API(`/user/favorites/${id}`)
      this.setState({
        isFavorite: res.data.body.isFavorite
      })
    }
  }

  async componentDidMount() {
    await this.getHouseInfo()
    this.renderMap(this.state.houseData.community, this.state.houseData.coord)
    this.checkFavorite()
  }

  render() {
    const { houseData, flag, isFavorite } = this.state

    return (
      <div className={styles.houseDetail} key={houseData.houseCode}>
        {/* 顶部导航栏 */}
        <NavHeader className={styles.navHeader} rightContent={[<i key='share' className='iconfont icon-share' />]}>{houseData.community}</NavHeader>
        {/* 轮播图 */}
        <div className={styles.swipers}>
          {
            flag ? (
            <Carousel
              autoplay
              autoplayInterval={3000}
              infinite
            >
              {this.renderSwipers()}
            </Carousel>
            ) : null
          }
        </div>
        {/* 房屋信息 */}
        <div className={styles.houseInfo}>
          <div className={styles.hosueInfoHeader}>
            <div className={styles.title}>
              {houseData.title}
            </div>
            <div className={styles.tagBox}>
              {
                flag ? houseData.tags.map((tag, id) => {
                  let tagId = 'tag' + (id + 1)%3
                  return (
                    <span className={[styles.tag, styles[tagId]].join(' ')} key={tag}>{tag}</span>
                  )
                }) : null
              }
            </div>
          </div>
          <div className={styles.houseInfoBody}>
            <div className={styles.bodyInfo}>
              <div className={styles.number}>{houseData.price}/月</div>
              <div className={styles.word}>租金</div>
            </div>
            <div className={styles.bodyInfo}>
              <div className={styles.number}>{houseData.roomType}</div>
              <div className={styles.word}>房型</div>
            </div>
            <div className={styles.bodyInfo}>
              <div className={styles.number}>{houseData.size}平米</div>
              <div className={styles.word}>面积</div>
            </div>
          </div>
          <div className={styles.houseInfoFooter}>
            <div className={styles.footerInfo}>
              <div className={styles.footerHeader}>装修：</div>
              <div className={styles.footerDesc}>精装</div>
            </div>
            <div className={styles.footerInfo}>
              <div className={styles.footerHeader}>朝向：</div>
              <div className={styles.footerDesc}>{houseData.oriented}</div>
            </div>
            <div className={styles.footerInfo}>
              <div className={styles.footerHeader}>楼层：</div>
              <div className={styles.footerDesc}>{houseData.floor}</div>
            </div>
            <div className={styles.footerInfo}>
              <div className={styles.footerHeader}>类型：</div>
              <div className={styles.footerDesc}>普通住宅</div>
            </div>
          </div>
        </div>
        {/* 房屋位置 */}
        <div className={styles.map}>
          <header className={styles.mapHeader}>{houseData.community}</header>
          <div id="map" className={styles.mapBody}></div>
        </div>
        {/* 房屋配套 */}
        <div className={styles.housePackage}>
          <HousePackage nameList={houseData.supporting}></HousePackage>
        </div>
        {/* 房屋概况 */}
        <div className={styles.set}>
          <div className={styles.setHeader}>房源概况</div>
          <div className={styles.setBody}>
            <div className={styles.user}>
              <div className={styles.avatar}>
                <img src={`${BASE_URL}/img/avatar.png`} className={styles.img} alt="" />
              </div>
              <div className={styles.userInfo}>
                <div>王女士</div>
                <div className={styles.userAuth}>
                  <i className="iconfont icon-auth" />
                  已认证房主
                </div>
              </div>
              <div className={styles.sendMsg}>
                <div className={styles.button}>发消息</div>
              </div>
            </div>
            <div className={styles.desc}>
              {houseData.description || '暂无描述'}
            </div>
          </div>
        </div>
        {/* 底部按钮 */}
        <div className={styles.footer}>
          <div className={[styles.left, isFavorite ? styles.favorite : ''].join(' ')} onClick={this.changeFavorite}>
            <img src={BASE_URL + (isFavorite ? '/img/star.png' : '/img/unstar.png')} alt='' className={styles.img}/>
            {isFavorite ? '已收藏' : '收藏'}
            </div>
          <div className={styles.center}>在线咨询</div>
          <div className={styles.right}>电话预约</div>
        </div>
      </div>
    )
  }
}